<template>
  <div class="news-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
              新闻资讯
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              了解贵港文旅最新动态，掌握第一手资讯
            </p>
          </div>
          <el-button
            class="back-btn"
            type="primary"
            plain
            @click="router.push('/')"
          >
            <el-icon class="mr-1"><Back /></el-icon>
            返回首页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 搜索和筛选区 -->
          <div
            class="search-filter-section bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-8"
          >
            <!-- 搜索框 -->
            <div class="search-box mb-6">
              <el-input
                v-model="searchQuery"
                placeholder="搜索新闻标题或关键词"
                class="search-input"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>

            <!-- 筛选条件 -->
            <div class="filter-conditions flex items-center gap-4">
              <!-- 分类筛选 -->
              <el-select
                v-model="filterConditions.category"
                placeholder="新闻分类"
                clearable
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>

              <!-- 时间筛选 -->
              <el-select
                v-model="filterConditions.timeRange"
                placeholder="发布时间"
                clearable
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="time in timeRanges"
                  :key="time.value"
                  :label="time.label"
                  :value="time.value"
                />
              </el-select>

              <!-- 排序方式 -->
              <el-select
                v-model="filterConditions.sortBy"
                placeholder="排序方式"
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="sort in sortOptions"
                  :key="sort.value"
                  :label="sort.label"
                  :value="sort.value"
                />
              </el-select>
            </div>
          </div>

          <!-- 新闻列表 -->
          <div class="news-list space-y-6" v-loading="loading">
            <div
              v-for="news in newsList"
              :key="news.id"
              class="news-card bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-all duration-300 transform hover:-translate-y-1 cursor-pointer"
              @click="handleNewsClick(news)"
            >
              <div class="flex">
                <div class="news-image-wrapper w-1/3">
                  <el-image
                    :src="news.image"
                    class="w-full h-48 object-cover"
                    fit="cover"
                  >
                    <template #placeholder>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="news-content flex-1 p-6">
                  <div class="news-meta flex items-center gap-4 mb-3">
                    <el-tag
                      size="small"
                      :type="getCategoryType(news.category)"
                      effect="light"
                    >
                      {{ news.category }}
                    </el-tag>
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                      {{ formatTime(news.date) }}
                    </span>
                  </div>
                  <h3
                    class="news-title text-xl font-medium text-gray-900 dark:text-white mb-3 line-clamp-2"
                  >
                    {{ news.title }}
                  </h3>
                  <p
                    class="news-summary text-gray-600 dark:text-gray-400 line-clamp-2 mb-4"
                  >
                    {{ news.summary }}
                  </p>
                  <div class="news-footer flex items-center justify-between">
                    <div class="news-author flex items-center">
                      <el-avatar
                        :size="24"
                        :src="news.author.avatar"
                        class="mr-2"
                      />
                      <span class="text-sm text-gray-600 dark:text-gray-400">
                        {{ news.author.name }}
                      </span>
                    </div>
                    <div
                      class="news-stats flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400"
                    >
                      <span class="flex items-center">
                        <el-icon class="mr-1"><View /></el-icon>
                        {{ formatNumber(news.views) }}
                      </span>
                      <span class="flex items-center">
                        <el-icon class="mr-1"><ChatDotRound /></el-icon>
                        {{ formatNumber(news.comments) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && !newsList.length"
              description="暂无相关新闻"
            >
              <el-button type="primary" @click="resetFilters"
                >清除筛选</el-button
              >
            </el-empty>

            <!-- 分页 -->
            <div
              v-if="total > 0"
              class="pagination-wrapper flex justify-center mt-8"
            >
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 热门新闻 -->
          <div
            class="hot-news bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Star /></el-icon>
              热门资讯
            </h3>
            <div class="hot-news-list space-y-4">
              <div
                v-for="news in hotNews"
                :key="news.id"
                class="hot-news-item flex items-start gap-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-lg transition-all duration-300"
                @click="handleNewsClick(news)"
              >
                <el-image
                  :src="news.image"
                  class="w-20 h-20 rounded-lg object-cover flex-shrink-0"
                />
                <div class="flex-1 min-w-0">
                  <h4
                    class="text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-1"
                  >
                    {{ news.title }}
                  </h4>
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ formatTime(news.date) }}
                  </div>
                  <div
                    class="mt-1 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400"
                  >
                    <span class="flex items-center">
                      <el-icon class="mr-1"><View /></el-icon>
                      {{ formatNumber(news.views) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 新闻分类 -->
          <div
            class="news-categories bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Menu /></el-icon>
              新闻分类
            </h3>
            <div class="categories-list space-y-2">
              <div
                v-for="category in categories"
                :key="category.value"
                class="category-item flex items-center justify-between p-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-all duration-300"
                @click="handleCategoryClick(category)"
              >
                <span class="text-gray-700 dark:text-gray-300">{{
                  category.label
                }}</span>
                <el-tag size="small" :type="category.type" effect="light">{{
                  category.count
                }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  Search,
  Back,
  View,
  ChatDotRound,
  Picture,
  Star,
  Menu,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import { newsListData, categoriesData, timeRangesData, sortOptionsData } from './newsData';

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 筛选条件
const filterConditions = reactive({
  category: "",
  timeRange: "",
  sortBy: "newest",
});

// 新闻分类
const categories = categoriesData;

// 时间范围选项
const timeRanges = timeRangesData;

// 排序选项
const sortOptions = sortOptionsData;

// 新闻列表数据
const newsList = ref([]);

// 从测试数据中随机选择热门新闻
const getRandomHotNews = () => {
  // 复制数组以避免影响原始数据
  const shuffled = [...newsListData].sort(() => 0.5 - Math.random());
  // 获取前3条作为热门新闻
  return shuffled.slice(0, 3);
};

// 热门新闻数据
const hotNews = ref([]);

// 获取新闻列表
const getNewsList = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取新闻列表API
    const response = await new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          items: newsListData,
          total: newsListData.length,
        });
      }, 500);
    });

    newsList.value = response.items;
    total.value = response.total;
  } catch (error) {
    console.error("获取新闻列表失败:", error);
    ElMessage.error("获取新闻列表失败");
    // 使用测试数据作为后备
    newsList.value = newsListData;
    total.value = newsListData.length;
  } finally {
    loading.value = false;
  }
};

// 获取热门新闻
const getHotNews = () => {
  hotNews.value = getRandomHotNews();
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 获取分类标签类型
const getCategoryType = (category) => {
  const categoryItem = categories.find((item) => item.label === category);
  return categoryItem?.type || "";
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getNewsList();
};

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1;
  getNewsList();
};

// 重置筛选
const resetFilters = () => {
  searchQuery.value = "";
  Object.assign(filterConditions, {
    category: "",
    timeRange: "",
    sortBy: "newest",
  });
  currentPage.value = 1;
  getNewsList();
};

// 处理新闻点击
const handleNewsClick = (news) => {
  router.push(`/news/${news.id}`);
};

// 处理分类点击
const handleCategoryClick = (category) => {
  filterConditions.category = category.value;
  currentPage.value = 1;
  getNewsList();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getNewsList();
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getNewsList();
};

// 页面加载时获取数据
onMounted(() => {
  getNewsList();
  getHotNews();
});
</script>

<style lang="scss" scoped>
.news-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .image-placeholder {
    @apply flex items-center justify-center w-full h-full bg-gray-200 dark:bg-gray-700;
    .el-icon {
      @apply text-4xl text-gray-400 dark:text-gray-500;
    }
  }

  .news-card {
    &:hover {
      .news-title {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }

  .hot-news-item {
    &:hover {
      h4 {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }
}
</style>
